package org.rslai.util.process;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 执行外部程序
 * @author rslai
 */
public abstract class AbstractProcess implements Process {

	/**
	 * 运行一个外部程序
	 * @param command 要执行的可执行文件的完整路径及参数(文件格式为 EXE,BAT,COM 或 PIF)
	 * @param workingDirectory 工作目录.不一定非得是程序所在的目录. 传入 null 为缺省目录
	 * @param waitFor 是否等待该程序执行完毕
	 * @return 外部程序运行后返回的信息
	 * @throws Exception
	 */
	private String run(String command, String workingDirectory, boolean waitFor) throws IOException {
		StringBuffer result = new StringBuffer();
		BufferedReader bufferedreader = null;
		try {
			// 运行外部程序
			Runtime runtime = Runtime.getRuntime();
			java.lang.Process process;
			if (workingDirectory == null) {
				process = runtime.exec(command);
			} else {
				process = runtime.exec(command, null, new java.io.File(workingDirectory));
			}

			// 等待执行结束并返回执行结果
			if (waitFor) {
				bufferedreader = new BufferedReader(new InputStreamReader(process.getInputStream()));
				String line = null;
				while ((line = bufferedreader.readLine()) != null) {
					result.append(line);
					result.append("\r\n");
				}
			}
		} catch (IOException ioException) {
			throw ioException;
		} finally {
			if (bufferedreader != null) {
				try {
					bufferedreader.close();
				} catch (Exception ex) {
				}
			}
		}

		return result.toString();
	}

	@Override
	public boolean run(String command, String workingDirectory) throws IOException {
		return "".equals(this.run(command, workingDirectory, false));
	}

	@Override
	public boolean run(String command) throws IOException {
		return "".equals(this.run(command, null, false));
	}

	@Override
	public String runWait(String command, String workingDirectory) throws IOException {
		return this.run(command, workingDirectory, true);
	}

	@Override
	public String runWait(String command) throws IOException {
		return this.run(command, null, true);
	}

	@Override
	public int processExists(String process) throws IOException {
		throw new IllegalArgumentException("方法 processExists(String process) 未实现！");
	}

	@Override
	public boolean processClose(String process) throws IOException {
		throw new IllegalArgumentException("方法 processClose(String process) 未实现！");
	}

}
